<template>
  <el-dialog
    class="set-responsible-person-modal"
    append-to-body
    :title="title"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(550)"
    :before-close="handleCancel">
    <div class="form-container">
      <el-form
        :model="ruleForm"
        :rules="rules"
        size="medium"
        ref="ruleForm"
        class="rule-form"
        :label-width="$setRem(130)"
      >
        <el-form-item label="初审责任人" prop="roleId" required>
          <el-select
            placeholder="请选择角色"
            clearable
            filterable
            v-model="ruleForm.roleId">
            <el-option
              v-for="v in roleList"
              :label="v.roleName"
              :value="v.id"
              :key="v.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer" slot="footer">
      <el-button type="primary" @click="handleCancel">取 消</el-button>
      <el-button
        class="success"
        type="primary"
        :loading="loading"
        @click="hanldeSave">
        保 存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '设置责任人'
    },
    roles: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      userList: [],
      roleList: [], // 项目角色
      ruleForm: {
        roleId: ''
      },
      rules: {
        roleId: [
          { required: true, message: '请选择角色' }
        ],
      }
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    }
  },
  watch: {
    // 监听弹框显示/隐藏
    visible(data) {
      if (!data) {
        Object.keys(this.ruleForm).forEach(key => {
          this.ruleForm[key] = '';
        });
        return;
      }
      this.getRoleList();
    },
  },
  methods: {
    /**
     * 获取项目角色信息
     */
    async getRoleList() {
      if (!this.projectId) return;
      const params = {
        projectId: this.projectId,
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getRoleList(params);
      if (success && data) {
        this.roleList = data.list || [];
        if (this.roles) {
          this.ruleForm.roleId = this.roles.roleId || '';
        }
      }
    },
    hanldeSave() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$emit('submit', this.ruleForm);
        }
      });
    },
    // 取消
    handleCancel() {
      this.$emit('cancel');
    }
  },
};
</script>

<style lang="scss" scoped>
  @import "../../../assets/styles/dialog";
  .set-responsible-person-modal {
    .form-container {
      width: 100%;
      padding: 20px 20px 20px 0;
    }
  }
</style>
